<template>
  <el-drawer
    v-model="visible"
    :title="title"
    size="600px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <template #header>
      <div class="flex justify-between mr-2">
        <div class="text-black font-bold">{{ title }}</div>
      </div>
    </template>
    <!-- 加载状态 -->
    <div v-loading="loading" class="log-detail-content">
      <!-- 操作基本信息 -->
      <div v-if="logDetail" class="basic-info-section">
        <div class="info-grid">
          <div class="info-item">
            <span class="label">操作者：</span>
            <span class="value">{{ logDetail.operateName || "未知" }}</span>
          </div>
          <div class="info-item">
            <span class="label">操作时间：</span>
            <span class="value">{{
              formatDateTime(logDetail.operateTime)
            }}</span>
          </div>
        </div>
      </div>

      <!-- 操作数据详情 -->
      <div v-if="logDetail" class="operation-data-section">
        <div class="section-title">操作详情</div>

        <!-- 补充报告所属人 (operateType: 10) -->
        <div class="info-item mb-4">
          <span class="value operation-type">{{
            logDetail.operateTypeName || "未知操作"
          }}</span>
        </div>

        <div
          v-if="logDetail.operateType === 10 && logDetail.operateData"
          class="data-content"
        >
          <el-descriptions
            direction="vertical"
            :column="2"
            :size="'small'"
            border
          >
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">姓名</div>
              </template>
              {{ logDetail.operateData[0] }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">用户ID</div>
              </template>
              {{ logDetail.operateData[1] }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审核结果 (operateType: 11) -->
        <div
          v-else-if="logDetail.operateType === 11 && logDetail.operateData"
          class="data-content"
        >
          <el-descriptions
            :column="2"
            direction="vertical"
            :size="'small'"
            border
          >
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">指标名称</div>
              </template>
              {{ logDetail.operateData[0] }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">识别结果</div>
              </template>
              {{ logDetail.operateData[1] }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">参考范围</div>
              </template>
              {{ logDetail.operateData[2] }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { addReportApi, type ReportOperateLogDetailVO } from "@/api/addReport";

// Props 定义
interface Props {
  modelValue?: boolean;
  operateLogId?: number;
  title?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  operateLogId: 0,
  title: ""
});

// Emits 定义
const emit = defineEmits<{
  "update:modelValue": [value: boolean];
}>();

// 响应式数据
const loading = ref(false);
const logDetail = ref<ReportOperateLogDetailVO | null>(null);

// 计算属性：控制抽屉显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    console.log("抽屉状态变更:", value);
    emit("update:modelValue", value);
  }
});

// 监听抽屉打开状态，自动加载数据
watch(
  () => props.modelValue,
  newValue => {
    console.log(
      "监听到抽屉状态变化:",
      newValue,
      "操作日志ID:",
      props.operateLogId
    );
    if (newValue && props.operateLogId) {
      loadLogDetail();
    }
  },
  { immediate: true }
);

// 监听操作日志ID变化
watch(
  () => props.operateLogId,
  newId => {
    console.log("监听到操作日志ID变化:", newId);
    if (props.modelValue && newId) {
      loadLogDetail();
    }
  }
);

/**
 * 加载操作日志详情数据
 * 调用API获取详细的操作日志信息
 */
const loadLogDetail = async () => {
  if (!props.operateLogId) {
    console.warn("操作日志ID为空，无法加载详情");
    return;
  }

  try {
    console.log("开始加载操作日志详情，ID:", props.operateLogId);
    loading.value = true;
    logDetail.value = null;

    // 调用API获取操作日志详情
    const response = await addReportApi.getOperateLogDetail({
      operateLogId: props.operateLogId
    });

    console.log("操作日志详情API响应:", response);

    if (response.code === 0 && response.data) {
      logDetail.value = response.data;
      console.log("操作日志详情加载成功:", logDetail.value);
    } else {
      const errorMsg = response.message || "获取操作日志详情失败";
      console.error("操作日志详情加载失败:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    const errorMsg = "网络请求失败，请稍后重试";
    console.error("操作日志详情加载异常:", err);
    ElMessage.error(errorMsg);
  } finally {
    loading.value = false;
    console.log("操作日志详情加载完成");
  }
};

/**
 * 格式化日期时间
 * @param dateTime 日期时间字符串
 * @returns 格式化后的日期时间字符串
 */
const formatDateTime = (dateTime?: string): string => {
  if (!dateTime) return "未知时间";

  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return dateTime;

    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit"
    });
  } catch (err) {
    console.warn("日期格式化失败:", err);
    return dateTime;
  }
};

// 对外暴露的方法
defineExpose({
  /**
   * 手动刷新数据
   * 外部组件可以调用此方法重新加载日志详情
   */
  refresh: loadLogDetail
});
</script>

<style lang="scss" scoped>
.log-detail-content {
  min-height: 400px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e4e7ed;
  }

  // 基本信息区域
  .basic-info-section {
    margin-bottom: 24px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 16px;

    .info-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 16px;

      .info-item {
        display: flex;
        align-items: center;
        border-radius: 6px;

        .label {
          font-weight: 500;
          color: #606266;
          min-width: 80px;
        }

        .value {
          color: #303133;
          flex: 1;
        }
      }
    }
  }

  .operation-data-section {
    padding: 5px;
    .operation-type {
      font-weight: 600;
      color: #409eff;
      font-size: 14px;
      font-weight: 500;
      color: #606266;
      margin-bottom: 12px;
    }
  }
}
</style>
